package aichess;

import java.util.concurrent.TimeUnit;

/**
 * Class that implements Depth-First Search
 * @author DumbStation
 */
public class DFS {
    private static int nodes = 0;
    private static long start = 0;
    private static long finish = 0;
    private static MoveValue mv;
    
    /**	dfs: checks with minimax the moves of the pieces and if there is a checkmate in the search-tree.
    *	@param board board to analyze.
    **/
    public static MoveValue dfs(Board board){
        mv = new MoveValue();
        start = System.nanoTime();
        if(!board.isCheckMate() || !board.isStalemate()){
            Move[] movements = board.getValidMoves();
            for(Move a:movements){
                Board clone = board.clone();
                clone.makeMove(a);
                nodes++;
                mv.setMove(a);
                mv.setValue(minimax(clone));
            }
        }
        finish = System.nanoTime();
        System.out.println("Expanded nodes: " + nodes);
        System.out.println("Elapsed time: " + TimeUnit.MILLISECONDS.convert(finish-start, TimeUnit.NANOSECONDS) + "ms");
        return mv;
    }
    
    /**	DFS version of minimax.
    *	@param board board to analyze. 
    **/
    public static int minimax(Board board){
        int max = -99999;
        if(!board.isStalemate() || !board.isCheckMate() && board.movestodraw >= 1){
            Move[] movements = board.getValidMoves();
            for(Move a:movements){
                Board clone = board.clone();
                clone.makeMove(a);
                nodes++;
                mv.setMove(a);
                int minmax = -(minimax(clone));
                if(max > minmax){
                    mv.setValue(max);
                    return max;
                }
                mv.setValue(minmax);
                return minmax;
            }
        }
        if(board.isCheckMate()){
            return 1;
        }
        return 0;
    }
}
